package filesystem.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileHasher 
{
	private static String algorithm = "SHA-512";
	
	public FileHasher()
	{
		
	}
	
	public static String getHashValue(String filename)
	{	
		// Read file
		FileChannel channel = null;
		ByteBuffer buffer = null;
		
		try
		{
	        channel = new RandomAccessFile(filename, "r").getChannel();
	        buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int)channel.size());
	        channel.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return null;
		}
		finally
		{
			try
			{
				if (channel != null)
					channel.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		
		// Create message digest
        MessageDigest messageDigest = null;
        
        try
        {
        	messageDigest = MessageDigest.getInstance(algorithm);
        	messageDigest.update(buffer.duplicate());
        }
        catch (NoSuchAlgorithmException e)
        {
        	// Should not happen
        	e.printStackTrace();
        	return null;
        }        
        
        byte[] digest = messageDigest.digest(); 
        
        return toHexString(digest);
	}
	
	public static String toHexString (byte[] b)
	{
		String hexString = new BigInteger(1, b).toString(16);  
       
		if (hexString.length() % 2 != 0) {
			hexString = "0" + hexString;
        }
		return hexString;
	}  

    
    public static void main(String[] args) throws Exception 
    {
    	 String readLine = ""; // Line read from standard in
    	     	 
    	 InputStreamReader converter = new InputStreamReader(System.in);
    	 BufferedReader in = new BufferedReader(converter);
    	 
    	 while (!readLine.equals("quit"))
    	 {
    		 System.out.println("Enter a line of text (type 'quit' to exit): ");
    		 readLine = in.readLine();
    		 if (readLine.equals("quit"))
    		 {
    			 System.out.println("Bye!");
    			 break;
    		 }	 
    		  
    	     System.out.println("Hash value:" + getHashValue(readLine));    			 
    	 }
     }  
}
